package cn.yuanqiao.activiti.listener;

import cn.yuanqiao.activiti.aspect.AuthService;

import cn.yuanqiao.activiti.util.SecurityUtil;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.system.service.ISysUserService;
import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.util.SimpleContext;
import org.activiti.api.model.shared.model.VariableInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.bpmn.model.*;
import org.activiti.engine.*;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import java.util.*;

/**
 * @ClassName: WritsArchiveBorrowListener
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2023/6/5 19:24
 * @Blog: huahuacoco.top
 */

@Component("GetNextAssigneeListener")
public class GetNextAssigneeListener implements TaskListener,ExecutionListener {

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private SecurityUtil securityUtil;



    @Override
    public void notify(DelegateTask task) {
        Object obj = task.getExecution().getVariable("nextAssignee");
        String processInstanceId = task.getProcessInstanceId();
        String processDefinitionId = task.getProcessDefinitionId();
        try {
            //String s = nextPrcessApprover(processInstanceId,processDefinitionId,(TaskEntityImpl)task);
            //System.out.println(s);
            System.out.println("==============>");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (obj != null){
            taskService.setAssignee(task.getId(),String.valueOf(obj));
        }

    }

    @Override
    public void notify(DelegateExecution execution) {
        System.out.println(111);
        Map<String, Object> variables = execution.getVariables();
        String currentActivityId = execution.getCurrentActivityId();
        System.out.println(111);

    }

    public void create(DelegateTask delegateTask){
        System.out.println("============TaskListener start============");
        String taskDefinitionKey = delegateTask.getTaskDefinitionKey();
        String eventName = delegateTask.getEventName();
        System.out.println("事件名称:" + eventName);
        System.out.println("taskDefinitionKey:" + taskDefinitionKey);
        System.out.println("============TaskListener end============");

    }

    public  void getNextAssignee(String processId){
        //根据流程id获得流程模式id
        String processDefinitionId  = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult().getProcessDefinitionId();
        //获得流程模型
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        //获得模式中所有节点
        Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();

    }

    /**
     * 获得下一个节点的审批人或者节点名字
     * @param processId 流程实例id
     * @return
     * @throws Exception
     */
    public Map<String, Object> nextPrcessApprover(String processId,String processDefinitionId,Task thisTask)throws Exception{
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        //获得流程当前所处位置
        //List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processId).list();
        List<Task> actRuTasks = processEngine.getTaskService().createTaskQuery().processInstanceId(processId).list();
        //actRuTasks.add(thisTask);
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);

        //最终usertask节点
        //List<FlowElement> userTasks = new ArrayList<>();
        Map<String,FlowElement> userTasks = new HashMap<>();
        if(model != null&&actRuTasks!=null&&actRuTasks.size()!=0) {
            //获得流程模型的所有节点
            Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
            //遍历节点
            for(FlowElement e : flowElements) {
                for(Task task : actRuTasks){
                    String currentKey = task.getTaskDefinitionKey();
                    //
                    if(StringUtils.isNotEmpty(currentKey)){
                        //获得当前节点
                        if(e.getId().equals(currentKey)){
                            if(e instanceof UserTask){
                                List<SequenceFlow> currentUser =  ((UserTask) e).getOutgoingFlows();
                                //获得流程中的所有变量信息

                                List<VariableInstance> actRuVariables = processRuntime.variables(ProcessPayloadBuilder
                                        .variables()
                                        .withProcessInstanceId(processId)
                                        .build()
                                );
                                //List<VariableInstanceEntityImpl> actRuVariables = runtimeService..getVariableByProcessId(processId);
                                for (SequenceFlow s : currentUser){
                                    nextNode(flowElements,s,actRuVariables,userTasks,null);
                                }
                            }
                        }
                    }
                }

            }
        }

        StringBuffer sb = new StringBuffer();
        Map<String,Object> userList = new HashMap<>();
        List<VariableInstance> actRuVariables = processRuntime.variables(ProcessPayloadBuilder
                .variables()
                .withProcessInstanceId(processId)
                .build()
        );
        AuthService authService = null;
        for (VariableInstance item : actRuVariables) {
            if (item.getName().equals("authService")){
                authService = item.getValue();
                break;
            }
        }
        for(Map.Entry<String,FlowElement> item : userTasks.entrySet()){
            String elExpression = item.getKey();
            String key = "${is_agree == 1}".equalsIgnoreCase(elExpression)?"agreeUserList":"${is_agree == 0}".equalsIgnoreCase(elExpression)?"notAgreeUserList":"otherUserList";
            FlowElement e = item.getValue();
            if(e instanceof UserTask){
                List<String> l =((UserTask) e).getCandidateGroups();
                List<TreeSelect> treeSelects = new ArrayList<>();
                for(String s :l){
                    List<SysUser> sUsers = sysUserService.selectUserByRoleKey(s);
                    if(sUsers!=null&&sUsers.size()!=0){
                        //List<TreeSelect> treeSelects = new ArrayList<>();
                        for(SysUser sUser :sUsers){
                            TreeSelect treeSelect = new TreeSelect();
                            treeSelect.setId(sUser.getUserId());
                            treeSelect.setLabel(sUser.getNickName());
                            treeSelect.setNodeType("user");
                            treeSelects.add(treeSelect);
                            sb.append(sUser.getUserName()+"【用户】,");
                        }
                    }else{
                        sb.append(e.getName()+"【节点名称】,");
                    }
                }
                List<String> candidateUsers = ((UserTask) e).getCandidateUsers();

                for(String s :candidateUsers){
                    List<String> strings = null;
                    if ("${authService.deptLeader()}".equals(s)){
                        strings =  authService.deptLeader();
                    }else if ("${authService.archiveDeptLeader()}".equals(s)){
                        strings = authService.archiveDeptLeader();
                    }else if ("${authService.deptDagly()}".equals(s)){
                        strings = authService.deptDagly();
                    }
                    for(String s1 :strings){
                        SysUser sUser = sysUserService.selectUserByUserName(s1);
                        TreeSelect treeSelect = new TreeSelect();
                        treeSelect.setId(sUser.getUserId());
                        treeSelect.setLabel(sUser.getNickName());
                        treeSelect.setNodeType("user");
                        treeSelects.add(treeSelect);
                    }
                }
                String assignee = ((UserTask) e).getAssignee();
                if (assignee!=null&&!"".equals(assignee)){
                    String keyAssignee = "agreeUserList".equalsIgnoreCase(key)?"agreeAssignee":"notAgreeUserList".equalsIgnoreCase(key)?"notAgreeAssignee":"otherAssignee";
                    userList.put(keyAssignee,assignee);
                }
                if(treeSelects.size()!=0){
                    userList.put(key,treeSelects);
                }
            }else if(e instanceof EndEvent){
                sb.append(e.getName());
            }
        }
        return userList;
    }

    /**
     *
     * @param flowElements 该模型的所有节点
     * @param currentSequenceFlow 当前流程线
     * @param elKV  所有变量信息
     * @param userTasks 最终结果集
     * @throws Exception
     */
    private void nextNode(Collection<FlowElement> flowElements,SequenceFlow currentSequenceFlow,List<VariableInstance> elKV,Map<String,FlowElement> userTasks,String elExp)throws Exception{
        //获得当前线在
        String  SequenceFlowId =   currentSequenceFlow.getTargetRef();
        if (elExp == null){
            elExp = currentSequenceFlow.getConditionExpression();
        }
        for(FlowElement e : flowElements){
            if(e.getId().equals(SequenceFlowId)){
                //判断类型
                //如果是排他网管
                if(e instanceof ExclusiveGateway){
                    //默认流程线
                    String defaultFlowString = ((ExclusiveGateway) e).getDefaultFlow();
                    SequenceFlow defaultFlow = null;
                    List<SequenceFlow> egSequenceFlow  = ((ExclusiveGateway) e).getOutgoingFlows();
                    //标识
                    boolean boo = true;
                    for(int i=0;i<egSequenceFlow.size();i++){
                        if(egSequenceFlow.get(i).getId().equals(defaultFlowString)){
                            defaultFlow = egSequenceFlow.get(i);
                        }
                        if(!StringUtils.isEmpty(egSequenceFlow.get(i).getConditionExpression())){
                            //判断el选择路线
                            if(isCondition(egSequenceFlow.get(i).getConditionExpression(),elKV)){
                                boo=false;
                                //如果为真说明会走这条路线  递归
                                nextNode(flowElements,egSequenceFlow.get(i),elKV,userTasks,elExp);
                            }
                        }else{
                            continue;
                        }

                        //如果最后一个走完没有el为true的，则查看是否有默认流程，如果没有抛出异常
                        if(i==egSequenceFlow.size()-1&&boo){
                            if(StringUtils.isEmpty(defaultFlowString)){
                                throw  new Exception("流程异常");
                            }else{
                                //如果有默认流程 递归
                                nextNode(flowElements,defaultFlow,elKV,userTasks,elExp);
                            }
                        }
                    }
                    //如果是user用户审批节点
                }else if(e instanceof UserTask){
                    userTasks.put(elExp,e);
                }else if(e instanceof EndEvent){
                    userTasks.put(elExp,e);
                }
                // .... 现在就这么多
            }
        }
    }

    //判断 el 表达式
    private boolean isCondition( String el,List<VariableInstance> elKV) {
        ExpressionFactory factory = new ExpressionFactoryImpl();
        SimpleContext context = new SimpleContext();
        for(int i =0 ;i<elKV.size();i++){
            context.setVariable(elKV.get(i).getName(), factory.createValueExpression(elKV.get(i).getValue(), String.class));
            if ("archiveData".equals(elKV.get(i).getName())){
                List<LinkedHashMap<String,Object>> value = (List<LinkedHashMap<String,Object>>)elKV.get(i).getValue();
                LinkedHashMap<String, Object> map = value.get(0);
                if (map!=null){
                    for (Map.Entry<String,Object> item : map.entrySet()){
                        context.setVariable(item.getKey(), factory.createValueExpression(item.getValue(), String.class));
                    }
                }
            }
        }
        ValueExpression e = factory.createValueExpression(context, el, boolean.class);
        return (Boolean) e.getValue(context);
    }

}
